<template>
  <div class="successfulCase">
    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini"  @click="handleAdd" v-hasPermi="['system:menu:add']" >新增</el-button>
        </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tabelList" >
        <template v-for="(item,inx) in columnlist">
            <el-table-column :prop="item.prop" :label="item.label" min-width="100" align='center' :key='inx'></el-table-column>
        </template>
        <el-table-column align="center" width="150" label="接收函">
            <template slot-scope="scope">
                <div class="imgbox">
                    <template v-for='(it,inx) in scope.row.attachmentVOList'>
                        <el-image 
                        :key='inx'
                        style="width: 60px; height: 40px"
                        :src="it.fileUrl" 
                        :preview-src-list="scope.row | imglist">
                    </el-image>
                    </template>
                </div>
            </template>
        </el-table-column>
        <el-table-column align="center" width="100" label="操作">
            <template slot-scope="scope">
                <el-button @click="editItem(scope.row)" type='text'>编辑</el-button>
                <el-button @click="delItem(scope.row)" type='text'>删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div style="text-align:right;margin-top:20px;" v-if='queryParams.total>0'>
        <el-pagination background layout="prev, pager, next" @current-change="handleQuery" :current-page.sync="queryParams.pageNum" :page-size="queryParams.pageSize" :total="queryParams.total"> </el-pagination>
    </div>
    <mydialog :dialogTitle='dialogTitle' @handleClose='setShowDialog' @serve='serve' :show='showDialog'>
        <template slot="cont">
            <div class="mycont">
                <el-form v-model="form" label-width="120px" inlink>
                    <el-row>
                        <el-col :span='12'>
                            <el-form-item class="is-required" label="所属一级科目">
                                <el-select v-model="form.subjectId" placeholder="请选择">
                                    <el-option v-for="item in towArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span='12'>
                            <el-form-item label="影响因子">
                                <el-input v-model="form.impactFactor" placeholder="(示例:2.5)" maxlength="10"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span='12'>
                            <el-form-item label="中科院分区">
                                <el-select v-model="form.academyId" placeholder="请选择">
                                    <el-option v-for="item in fqArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span='12'>
                            <el-form-item label="用户昵称">
                                <el-input v-model="form.userNickName" placeholder="请输入用户昵称" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span='12'>
                            <el-form-item label="职业">
                                <el-input v-model="form.occupation" placeholder="请输入职业" maxlength="200"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span='12'>
                            <el-form-item label="评语">
                                <el-input v-model="form.comments" placeholder="请输入评语" maxlength="200"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span='12'>
                            <el-form-item label="接收函展示">
                                <el-upload
                                    :headers="headers"
                                    :action="uploadUrl"
                                    :before-upload="handleBeforeUpload"
                                    :on-success="handleUploadSuccess"
                                    :on-error="handleUploadError"
                                    name="file"
                                    :file-list="fileList"
                                    :before-remove='removeItem'
                                    ref="upload" >
                                    <el-button size="small" type="primary">点击上传</el-button>
                                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>
    </mydialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {addSuccessfulCase,selectAcademyInfos,selectSubjectInfos,selectSuccessfulCases,updateSuccessfulCase,getServiceRemove,getSuccessfulCaseById,deleteAttachment,addAttachment} from "@/api/pc.js"
export default {
  name: "successfulCase",
  data() {
    return {
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
            Authorization: "Bearer " + getToken()
        },
        statusArr:[
            {label:'未发布',value:'1' },
            {label:'服务中',value:'2' },
            {label:'已结束',value:'3' },
        ],//期刊状态
        showSearch:true,//展示搜索条件
        loading:false,//tabel的loading
        showDialog:false,//弹窗的loading
        queryParams:{name:'',pageNum:1,pageSize:10,total:0},
        tabelList:[],//列表
        fileList:[],//上传的数组
        fqArr:[],//分区
        towArr:[],//二级分类列表
        dialogTitle:'创建成功案例',//弹窗标题
        columnlist:[
            { label:'用户昵称', prop:'userNickName'},
            { label:'职业', prop:'occupation'},
            { label:'中科院分区', prop:'academyId'},
            { label:'影响因子', prop:'impactFactor'},
            { label:'评价', prop:'comments'},
            // { label:'接收函', prop:'comments'},
        ],
        newform:{
            subjectId:null,           //所属三级科目-名称
            subjectName:'',         //所属三级科目-名称
            impactFactor:'',        //影响因子
            academyName:'',         //中科院分区-名称
            academyId:null,           //中科院分区
            userNickName:'',        //用户昵称
            occupation:'',          //职业
            comments:'',            //评语
            attachmentVOList:[],    //附件信息
        },
        form:{},
    };
  },
  filters:{
    imglist(val){
        return val.attachmentVOList.map(it=>{return it.fileUrl});
    }
  },
  components: {},
  created(){ this.getfqdata(); this.getfl(); this.getdata();},
  mounted() {
    this.form = [].concat(this.newform)
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
    //   if(this.form.attachmentVOList.length>=2){
    //     this.$message({message:'只能上传两张图片',type:'warning'})
    //     return false;
    //   }
      return true;
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        // 获取光标所在位置
        console.log(res)
        // this.fileList.push({fileUrl:res.fileName,fileName:res.realName,attachmentId:'',name:res.realName})
        // this.form.attachmentVOList.push({fileUrl:res.fileName,fileName:res.realName,attachmentId:''})
        if(this.dialogTitle =='新增成功案例'){
        }else{
            let obj ={
                fileUrl:res.fileName,
                fileName:res.realName,
                typeId:this.form.caseId?this.form.caseId:''
            }
            addAttachment(obj).then(res2=>{
                if(res2.code==200){
                    this.fileList.push({fileUrl:res.fileName,fileName:res.realName,attachmentId:'',name:res.realName})
                    this.form.attachmentVOList.push({fileUrl:res.fileName,fileName:res.realName,attachmentId:''})
                }
            })
        }
      } else {
            this.$message.error(res.msg);
      }
    },
    handleUploadError() {
      this.$message.error("上传失败");
    },
    //删除文件
    removeItem(file,fileList,index){
        console.log(file)
        console.log(fileList)
        console.log(index)
        if(file.attachmentId!=""&&file.attachmentId!=null){
            deleteAttachment({attachmentId:file.attachmentId}).then(res=>{
                if(res.code==200){
                    this.fileList.splice(this.fileList.findIndex((profile) => profile.attachmentId === file.attachmentId),1)
                    this.form.attachmentVOList.splice(this.fileList.findIndex((profile) => profile.attachmentId === file.attachmentId),1)
                }
            })
            return true
        }else{
            return true
        }
    },
    // 删除
    delItem(val){
        this.$confirm('确定要删除此案例吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            getServiceRemove({serviceId:val.caseId}).then(res=>{
                if(res.code==200){
                    this.getdata();
                }
            })
        }).catch(() => {});
    },
    //编辑
    editItem(val){
        getSuccessfulCaseById({serviceId:val.caseId}).then(res=>{
            console.log(res)
            this.form = res.data;
            this.fileList = res.data.attachmentVOList.map(it=>{return {...it,name:it.fileName}});
            this.dialogTitle = '编辑成功案例';
            this.showDialog = true;
        })
    },
    //获取列表数组
    getdata(){
        var formData = new FormData();
            formData.append('pageNum',this.queryParams.pageNum)
            formData.append('pageSize',this.queryParams.pageSize)
        selectSuccessfulCases(formData).then(res=>{
            if(res.code==200){
                this.tabelList=res.rows;
                this.queryParams.total = res.total|| 0;
            }
        })
    },
    //获取分类
    getfl(){
        var formData = new FormData();
        formData.append('subjectType',1)
        selectSubjectInfos(formData).then(res=>{
            this.towArr = res.rows.map(it=>{return {label:it.subjectName,value:it.subjectId}});;
        })
    },
    // 获取分区列表
    getfqdata(){
        selectAcademyInfos().then(res=>{
            if(res.code==200){
                this.fqArr = res.data.map(it=>{return {label:it.academyName,value:it.academyId}});
            }
        })
    },
    //打开弹窗
    handleAdd(){
        this.fileList = [];
        this.dialogTitle = '新增成功案例';
        this.form = JSON.parse(JSON.stringify(this.newform));
        this.showDialog=true;
    },
    //关闭弹窗
    setShowDialog(){
        this.showDialog=false;
    },
    //保存
    serve(){
        if(this.form.impactFactor){
            var reg = /^[0-9]+(\.[0-9]{1,2})?$/
            var texst= new RegExp(reg);
            if(!texst.test(this.form.impactFactor)){
                return this.$message.warning('影响因子请填写数字类型的内容')
            }
        }
        if(this.dialogTitle=='新增成功案例'){
            addSuccessfulCase(this.form).then(res=>{
                if(res.code==200){
                    this.showDialog=false;
                    this.getdata();
                }
            })
        }else{
            updateSuccessfulCase(this.form).then(res=>{
                if(res.code==200){
                    this.showDialog=false;
                    this.getdata();
                }
            })
        }
    },
    //搜索
    handleQuery(){
        this.getdata();
    },
  },
};
</script>

<style lang='scss' scoped>
.successfulCase {
  width: 100%;
  height: 100%;
  padding: 20px;
}
.imgbox{
    width: 100%;
    display: block;
    

}
</style>
<style scoped>
/deep/.dialogBox .el-dialog{
    width: 740px;
    min-height: 400px;
}
/deep/.el-date-editor, /deep/.el-input, /deep/.el-select-dropdown__wrap {
    width: 200px;
}
.imgbox /deep/.el-image:last-child {margin-left: 10px;}
</style>